﻿#region imports

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using Codeplex.ODataTFS.Model.Entities;

#endregion

namespace Codeplex.ODataTFS.Model.Serialization
{
	public class TFSChangeProxy : TFSBaseProxy
	{
		public TFSChangeProxy(Uri uri, ICredentials credentials)
			: base(uri, credentials)
		{
		}

		public IEnumerable<Change> GetChangesByChangeset(int changesetId, int topRequestValue)
		{
			var key = GetChangesByChangesetKey(changesetId.ToString());

			if (Cache[key] == null)
			{
				Cache[key] = RequestChangesByChangeset(changesetId, topRequestValue);
			}

			return (IEnumerable<Change>) Cache[key];
		}

		private IEnumerable<Change> RequestChangesByChangeset(int changesetId, int topRequestValue)
		{
			var versionControlServer = TfsConnection.GetService<Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>();

			return versionControlServer.GetChangesForChangeset(changesetId, false, topRequestValue, null)
				.Select(c => c.ToModel(TfsConnection.Name, changesetId)).ToArray();
		}

		private string GetChangesByChangesetKey(string changeset)
		{
			return string.Format(CultureInfo.InvariantCulture, "TFSChangeProxy.GetChangesByChangeset_{0}", changeset);
		}
	}
}
